<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChOpSchemeSyncSwitchMapper;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;
use function FriendsOfHyperf\Lock\lock;
use function Hyperf\Collection\data_get;
use function Hyperf\Support\optional;

class ChOpSchemeSyncSwitchService extends AbstractService
{
    public $mapper;

    public function __construct(ChOpSchemeSyncSwitchMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * @param array $params
     * @return int
     */
    public function getInfo(array $params): int
    {
        $type = data_get($params,'type',0);

        $lock = lock("op_scheme_sync_switch:".$type.$params['uid'], 6);
        try {
            $lock->block(4);
            $info = $this->mapper->findByType($type);
            if(empty($info)){
                $switch = 0;
                $data = [
                    'uid' => $params['uid'],
                    'main_uid' => $params['main_uid'],
                    'type' => $type,
                    'switch' => $switch
                ];
                $this->mapper->save($data);
            }else{
                $switch = $info->switch;
            }
            return $switch;
        } catch (LockTimeoutException $e) {
            return 0;
        } finally {
            optional($lock)->release();
        }
    }

    public function changeSwitch(array $params): bool
    {
        $type = data_get($params,'type',0);
        $switch = data_get($params,'switch',0);
        $info = $this->mapper->findByType($type);
        if(empty($info)){
            throw new NormalStatusException('操作失败');
        }
        $info->switch = $switch;
        return $info->save();
    }
}